package com.oa.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.joneying.common.redis.RedisManager;
import com.joneying.common.web.response.Resp;
import com.oa.core.config.WechatConfig;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.core.utils.CompanyWechatUtil;
import com.oa.pm.service.IOrganizationService;
import com.oa.system.dto.MailListDTO;
import com.oa.system.dto.UserListDTO;
import com.oa.system.dto.UserPutDTO;
import com.oa.system.entity.User;
import com.oa.system.service.IUserService;
import com.oa.system.vo.*;
import com.simm.common.constant.SimmConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.joneying.common.annotation.CommonController;
import org.springframework.context.annotation.Description;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import org.springframework.web.bind.annotation.RestController;
import com.oa.core.BaseController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.validation.Valid;

/**
 * @author syb123
 * @since 2019-01-29
 */
@RestController
@RequestMapping("/user")
@Api(description = "用户表模块")
//@ApiIgnore
public class UserController extends BaseController {


    private final IUserService userService;


    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private RestTemplate restTemplate;



    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    @CommonController
    @Description("登录")
    @ApiOperation(value = "登录")
    public Resp<UserVO> login() throws Exception {
        String ticket = getCookie("ticket");
        return userService.login(ticket);
    }

    @GetMapping("/wx/login")
    @CommonController
    @Description("登录")
    @ApiOperation(value = "登录")
    public Resp<UserVO> wxlogin() {
        String ticket = getCookie("ticket");
        return userService.wxlogin(ticket);
    }

    @GetMapping("/wx/user/info")
    @CommonController
    @Description("用户信息")
    @ApiOperation(value = "用户信息")
    public Resp wxInfo(){
        String ticket = getCookie("ticket");

        UserVO userVO = (UserVO) redisManager.get(ticket);

        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s", ticket, userVO.getWechatId());

        return new Resp().success(restTemplate.getForObject(url, String.class));
    }

    @GetMapping("/wx/auth")
    public void wxauth(@ApiParam(required = true,value = "重定向url的key") @RequestParam(required = false) String redirectUrlKey) throws IOException {

        String code = request.getParameter("code");

        //1.判断code是否为空，如果先请求微信接口获取微信code
        if(StringUtils.isBlank(code)){
            String redirectUri = this.domain + request.getServletPath() + (StringUtils.isNotBlank(request.getQueryString()) ? ("?" + request.getQueryString()) : "");

            try {
                redirectUri = URLEncoder.encode(redirectUri, SimmConstant.SIMM_ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            String requestCodeUrl = CompanyWechatUtil.buildRequestCodeUrl(redirectUri);
            try {
                response.sendRedirect(requestCodeUrl);
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //2.从redis中取出token,如果为空或者失效则调用微信接口重新获取并更新至redis
        String token = CompanyWechatUtil.getToken();

        //3.调用微信接口获取用户openId
        String userId = CompanyWechatUtil.getUserId(code, token);

        User user = userService.selectOne(new EntityWrapper<User>().eq("wechat_id", userId));

        if(user == null){
            response.sendRedirect(WechatConfig.defaultGotoUrl + "/#/404");
            return;
        }

        redisManager.set(token, userId, 60 * 30);

        try {
            String url = WechatConfig.defaultGotoUrl + "/"+ (redirectUrlKey == null ? "" : redirectUrlKey) + "?ACCESS_TOKEN=" + token +
                    (StringUtils.isNotBlank(request.getQueryString()) ? ("&" + request.getQueryString()) : "");

            Cookie cookie = new Cookie("ticket", token);
            response.addCookie(cookie);
            response.sendRedirect(url);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.sendRedirect(WechatConfig.defaultGotoUrl + "/#/404");
        return;
    }


    @PostMapping("/list")
    @CommonController
    @Description("查询列表分页")
    @ApiOperation(value = "查询")
    public Resp<UserListVO> findUserList(@RequestBody UserListDTO userListDTO){
        return new Resp().success(userService.findUserList(userListDTO));
    }

    /**
     * 根据Id查询
     *
     * @param id id
     * @return Resp
     */
    @GetMapping("/{id}")
    @CommonController
    @Description("获取详细信息")
    @ApiOperation(value = "根据id查询")
    public Resp<UserDetailsVO> findById(@ApiParam(value = "id", required = true) @PathVariable String id) throws DataIsEmptyException {
        return userService.findUserDetailsById(id);
    }

    @GetMapping("/me")
    @CommonController
    @Description("获取登录用户信息")
    @ApiOperation(value = "获取登录用户信息")
    public Resp<UserDetailsVO> findMe() throws DataIsEmptyException {
        return userService.findUserDetailsById(getLoginUserId());
    }

    @GetMapping("/ids")
    @CommonController
    @Description("查询以逗号分隔")
    @ApiOperation(value = "根据id查询")
    public Resp<List<UserListVO>> findByIds(@ApiParam(value = "id", required = true) @RequestParam String ids) {
        List<UserListVO> userListVOS = new ArrayList<>();
        String[] idArr = ids.split(",");
        for(int i = 0; i < idArr.length; i++){
            User user = userService.selectById(idArr[i]);
            UserListVO userListVO = new UserListVO();
            userListVO.setName(user.getName());
            userListVO.setUserId(user.getId());
            userListVOS.add(userListVO);
        }

        return new Resp<List<UserListVO>>().success(userListVOS);
    }

    /**
     * 根据Id修改
     *
     * @param userPutDTO UserPutDTO
     * @return Resp
     */
    @PutMapping("")
    @CommonController
    @Description("根据id修改")
    @ApiOperation(value = "根据id修改")
    public Resp update(@ApiParam(value = "用户表对象") @RequestBody(required = false) @Valid UserPutDTO userPutDTO) {
        if(StringUtils.isEmpty(userPutDTO.getUsername())){
            Wrapper wrapper = new EntityWrapper();
            wrapper.where("username = {0}", userPutDTO.getUsername());

            int userCount = userService.selectCount(wrapper);
            if(userCount > 0){
                return new Resp().failure("该用户名已存在");
            }
        }
        if(userPutDTO.getAuthorizationStatus() != null){
            userPutDTO.setAuthorizationStatus(userPutDTO.getAuthorizationStatus() == 1 ? userPutDTO.getAuthorizationStatus() : 2);
        }

        User user = new User();
        BeanUtils.copyProperties(userPutDTO, user);

        if (userService.updateById(user)) {
            return new Resp().success();
        } else {
            return new Resp().failure();
        }
    }

    /**
     * 根据Id删除
     *
     * @param id id
     * @return Resp
     */
    @DeleteMapping("/{id}")
    @CommonController
    @Description("根据id删除")
    @ApiOperation(value = "根据id删除")
    public Resp delete(@ApiParam(value = "id", required = true) @PathVariable("id") String id) throws BusinessException, DataIsEmptyException {
        return userService.deleteUserById(id);
    }

    @PutMapping("/password")
    @CommonController
    @Description("修改密码")
    @ApiOperation(value = "修改密码")
    public Resp updatePassword(@ApiParam("新密码") @RequestParam String newPassword, @ApiParam("旧密码") @RequestParam String oldPassword){
        String userId = getLoginUserId();
        User user = userService.selectById(userId);
        if(user != null){
            if (!(newPassword.trim().length() >= 6)){
                return new Resp().failure();
            }
            if(oldPassword != null && newPassword != null) {
                if (user.getPassword().equals(oldPassword)){
                    User us = new User();
                    us.setId(userId);
                    us.setPassword(newPassword);
                    return new Resp().success(userService.updateById(us));
                }else{
                    return new Resp().failure();
                }
            }else{
                return new Resp().failure();
            }
        }else{
            return new Resp().failure();
        }
    }

    @GetMapping("/mail/list")
    @CommonController
    @Description("查询通讯录")
    @ApiOperation(value = "查询通讯录")
    public Resp<MailListVO> findMailList(MailListDTO<MailListVO> mailListDTO){
        return new Resp().success(userService.findMailList(mailListDTO));
    }


    @GetMapping("/list/organization")
    @CommonController
    @Description("根据组织ID查询用户")
    @ApiOperation(value = "根据组织ID查询用户")
    public Resp<UserByOrganizationVO> findUserByOrganization(@ApiParam("部门ID") @RequestParam(value = "departmentId", required = false) String departmentId, @ApiParam("公司ID") @RequestParam(value = "companyId", required = false) String companyId){
        return new Resp().success(userService.findUserByOrganization(departmentId, companyId));
    }

    @GetMapping("/mail/export")
    @CommonController
    @Description("导出通讯录")
    @ApiOperation(value = "导出通讯录")
    public void exportMailList(){
        userService.exportMailList(response);
    }

//    /**
//     * 新增
//     *
//     * @param userAddDTO UserAddDTO
//     * @return Resp
//     */
//    @PostMapping("")
//    @CommonController
//    @Description("新增")
//    @ApiOperation(value = "新增")
//    public Resp add(@ApiParam(value = "用户表对象") @RequestBody @Valid UserAddDTO userAddDTO) {
//        Wrapper wrapper = new EntityWrapper();
//        wrapper.where("username = {0}", userAddDTO.getUsername());
//
//        int userCount = userService.selectCount(wrapper);
//        if(userCount > 0){
//            return new Resp().failure("该用户名已存在");
//        }
//
//        userAddDTO.setAuthorizationStatus(userAddDTO.getAuthorizationStatus() == 1 ? userAddDTO.getAuthorizationStatus() : 2);
//
//        User user = new User();
//        BeanUtils.copyProperties(userAddDTO, user);
//
//        user.setCreateTime(new Date());
//        if (userService.insert(user)) {
//            return new Resp().success();
//        } else {
//            return new Resp().failure();
//        }
//    }
}
